/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package entities;

import graphics.WindowManager;
import java.awt.Image;
import java.awt.Point;
import java.util.Random;
import javax.swing.JPanel;
import willispace.Log;
import willispace.WilliSpace;

/**
 * Supply class
 * @author mateusz
 */
public class Supply extends Entity {

    /**
     * Minimum supply units
     */
    public static int minSupplyUnits = 100;
    /**
     * Max supply units
     */
    public static int maxSupplyUnits = 300;
    /**
     * tile associated with this supply
     */
    protected Tile associatedTile;
    /**
     * type of supply
     */
    protected Supplies type;
    /**
     * units
     */
    protected int units;

    private Random randomGenerator;

    /**
     * Creates new supply
     * @param t         associated tile
     * @param img       image
     * @param myName    name
     */
    public Supply(Tile t, Image img, String myName) {
        super(t.getXY(), img, WindowManager.fullScreenWindow.middlePanel, myName);
        this.associatedTile = t;

        randomGenerator = new Random();
        this.units = randomGenerator.nextInt(maxSupplyUnits - minSupplyUnits) + minSupplyUnits;
    }

    @Override
    protected void updateProperties() {
        super.updateProperties();
        properties.put("associatedTile", associatedTile.getIndexes().toString());
        properties.put("units", Integer.toString(units));
    }

    /**
     * Take units from supply. If supply has less than wanted, returned is all that supply has
     * @param takenUnits wanted units of supply
     * @return  units
     */
    public synchronized int takeUnits(int takenUnits){
        
        takenUnits = Math.min(this.units, takenUnits);
        
        substract(takenUnits);
        
        // destroy this supply if is empty
        if(isEmpty()){
            WilliSpace.removeSupply(this);  
        }
        
        updateProperties();
        
        return takenUnits;
    }
    
    /**
     * substract units of supply
     * @param units units to substract
     */
    protected void substract(int units){
        this.units -= units;
    }
    
    /**
     * 
     * @return tile associated
     */
    public Tile getAssociatedTile() {
        return associatedTile;
    }
    
    /**
     * 
     * @return true if supply is empty
     */
    public synchronized boolean isEmpty(){
        return units <= 0;
    }

    /**
     * destroy supply
     */
    public void destroy(){
        associatedTile.unassociateWithEntity();
        removeFromProperPanel();
    }
    
    /**
     * @return the type
     */
    public Supplies getType() {
        return type;
    }
}
